<template>
  <div>
    <!--搜索表单-->
    <div>
      <el-form :inline="true">
        <el-form-item label="角色名称">
          <el-input v-model="keyword" placeholder="角色名称" clearable />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearchSysRoles">
            搜索
          </el-button>
          <el-button type="info" @click="handleClear">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--添加按钮-->
    <div>
      <el-button type="success" @click="handleShowSavaRoleDialog" size="mini">
        添加
      </el-button>
      <hr style="margin-top:-2px" />
    </div>

    <!--展示数据的表格-->
    <div>
      <el-table :data="sysRoles" stripe style="width: 100%">
        <el-table-column type="index" label="编号" width="80" />
        <el-table-column prop="roleName" label="角色名称" width="180" />
        <el-table-column prop="roleCode" label="角色code" width="180" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              @click="handleShowUpdateSysRoleDialog(scope.row)"
              size="small"
              type="primary"
            >
              修改
            </el-button>
            <el-button
              @click="handleDelete(scope.row)"
              size="small"
              type="danger"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showAssignMenu(scope.row)"
            >
              分配菜单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--分页导航条-->
    <div>
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[1, 2, 3, 4, 5]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--新增角色对话框-->
    <div>
      <el-dialog v-model="dialogFormVisible" :title="title">
        <el-form :model="form">
          <el-form-item label="角色名称" label-width="120px">
            <el-input v-model="sysRole.roleName" />
          </el-form-item>
          <el-form-item label="角色Code" label-width="120px">
            <el-input v-model="sysRole.roleCode" />
          </el-form-item>
          <el-form-item label="角色描述" label-width="120px">
            <el-input v-model="sysRole.description" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button
              type="primary"
              :disabled="SaveSysRoleFlag"
              @click="handleSaveOrUpdateSysRole"
            >
              提交
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <!--给角色分配菜单的对话框-->
    <div>
      <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
        <el-form label-width="80px">
          <el-tree
            :data="sysMenuTreeList"
            show-checkbox
            ref="myTree"
            default-expand-all
            node-key="id"
            :props="defaultProps"
            :default-checked-keys="checkedMenuIds"
            :check-on-click-node="true"
          />
          <el-form-item>
            <el-button type="primary" @click="handleAssignMenus">
              提交
            </el-button>
            <el-button @click="dialogMenuVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {
  GetSysRolePage,
  DeleteSysRole,
  SaveSysRole,
  GetSysRoleById,
  UpdateSysRole,
} from '@/api/sysrole'
import { ElMessage, ElMessageBox } from 'element-plus'
import { GetMenuByRoleId, AssignMenuToRole } from '@/api/sysMenu'
import { ref, onMounted } from 'vue'
/*day07给角色分配菜单 */
//给角色分配菜单的对话框
let dialogMenuVisible = ref(false)
//对话框树形图需要的数据列表
let sysMenuTreeList = ref([])
//定义一个选中的菜单数
let checkedMenuIds = ref([])
let myTree = ref(null)
let RoleId = ref(0)
//对话框树形图解析数据时的配置
const defaultProps = {
  children: 'children',
  label: 'title',
}
//点击分配菜单的事件函数
const showAssignMenu = async row => {
  RoleId.value = row.id
  sysMenuTreeList.value = []
  checkedMenuIds.value = []
  const { data } = await GetMenuByRoleId(row.id)
  //data返回的是map，menus,checkedMenuIds
  sysMenuTreeList.value = data.menus
  checkedMenuIds.value = data.checkedMenuIds
  dialogMenuVisible.value = true
}
//提交分配菜单的事件函数
const handleAssignMenus = async () => {
  //用来获取页面中ref值为myTree的dom对象
  const { code, message } = await AssignMenuToRole(
    RoleId.value,
    myTree.value.getCheckedKeys()
  )
  if (+code === 200) {
    ElMessage.success('分配成功')
  } else {
    ElMessage.error(message)
  }
  dialogMenuVisible.value = false
  fetchData()
}

/**day07========== */
let keyword = ref('')
let pageNum = ref(1)
let pageSize = ref(3)
let total = ref(0)
let title = ref('新增角色')
//分页列表
let sysRoles = ref([])
//新增角色对话框的数据
let dialogFormVisible = ref(false)
let sysRole = ref({
  roleName: '',
  roleCode: '',
  description: '',
})
//对话框提交按钮的禁用状态
let SaveSysRoleFlag = ref(false)
//页面渲染后执行
onMounted(() => {
  fetchData()
})
//==查询分页数据的函数
const fetchData = async () => {
  const { code, message, data } = await GetSysRolePage(
    keyword.value,
    pageNum.value,
    pageSize.value
  )
  if (+code === 200) {
    //data表示分页数据
    console.log(code, message, data)
    //解析data:
    sysRoles.value = data.list
    total.value = data.total
    pageNum.value = data.pageNum
    pageSize.value = data.pageSize
  } else {
    ElMessage.error(message)
  }
}
//分页导航条 事件函数
//===每页记录条数改变时回调
const handleSizeChange = () => {
  fetchData()
}
//页码改变时回调
const handleCurrentChange = () => {
  fetchData()
}
//条件搜索事件函数
const handleSearchSysRoles = () => {
  //初始化页码和pageSize后再执行条件查询
  pageNum.value = 1
  pageSize.value = 3
  fetchData()
}
//重置条件事件函数
const handleClear = () => {
  pageNum.value = 1
  pageSize.value = 3
  keyword.value = ''
  fetchData()
}
//删除按钮点击事件
const handleDelete = row => {
  //弹出删除确认
  ElMessageBox.confirm(`您确认删除【${row.roleName}】吗?`, 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      //异步请求删除id对应的角色
      const { code, message } = await DeleteSysRole(row.id)
      if (+code === 200) {
        ElMessage.success(message)
        fetchData()
      } else {
        ElMessage.error(message)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
//显示新增角色对话框的事件函数
const handleShowSavaRoleDialog = () => {
  sysRole.value = {}
  title.value = '新增角色'
  //显示对话框
  dialogFormVisible.value = true
}
//新增角色对话框提交按钮事件函数
const handleSaveSysRole = async () => {
  //防止表单重复提交
  SaveSysRoleFlag.value = true
  const { code, message } = await SaveSysRole(sysRole.value)
  if (+code === 200) {
    ElMessage.success('新增成功')
    //刷新页面的数据
    pageNum.value = 100
    fetchData()
  } else {
    ElMessage.error(message)
  }
  //关闭对话框
  dialogFormVisible.value = false
  //取消按钮禁用状态
  SaveSysRoleFlag.value = false
}
//表格修改角色按钮弹出更新对话框的事件函数
const handleShowUpdateSysRoleDialog = async row => {
  const { code, message, data } = await GetSysRoleById(row.id)
  if (+code === 200) {
    title.value = '更新角色'
    sysRole.value = data
    dialogFormVisible.value = true
  } else {
    ElMessage.error(message)
  }
}
//新增或更新提交按钮的事件函数
const handleSaveOrUpdateSysRole = () => {
  if (sysRole.value.id) {
    //提交更新请求
    handleUpdateSysRole()
  } else {
    //提交新增请求
    handleSaveSysRole()
  }
}
//更新角色
const handleUpdateSysRole = async () => {
  //防止表单重复提交
  SaveSysRoleFlag.value = true
  const { code, message } = await UpdateSysRole(sysRole.value)
  if (+code === 200) {
    ElMessage.success('更新成功')
    //刷新页面的数据
    //pageNum.value=100
    fetchData()
  } else {
    ElMessage.error(message)
  }
  //关闭对话框
  dialogFormVisible.value = false
  //取消按钮禁用状态
  SaveSysRoleFlag.value = false
}
</script>
